/*
 * @Author: GY19531 418941369@qq.com
 * @Date: 2022-09-05 14:48:08
 * @LastEditors: GY19531 418941369@qq.com
 * @LastEditTime: 2022-09-09 15:58:37
 * @FilePath: \one-web\src\pages\RemindManage\Component\JoinRemindPeopleRight.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { AutoComplete, Card, Col, Empty, Input, Row, Tooltip } from 'antd';
import { RemindManageAPI } from '../common/type';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { IActionEnum, RemindPeopleContext } from '../common';
import { ChangeEvent, useContext, useEffect, useMemo, useState } from 'react';
import MyIcon from '@/components/MyIcon';

const JoinRemindPeopleRight: React.FC<RemindManageAPI.IJoinCopyGiveRightCard> = () => {
  const {
    updateDispath,
    joinCheckBoxKeys,
    copyCheckBoxKeys,
    joinCheckBoxRows,
    copyCheckBoxRows,
    centreUserRows,
    centreUserRowsCopy,
  } = useContext(RemindPeopleContext);
  const [rightSearchValue, setRightSearchValue] = useState<string>('');
  /**
   * 判断已选数量和未选数量
   */
  const isLength = useMemo(() => {
    let selected: any = '0';
    let noSelect: any = '0';
    selected = joinCheckBoxKeys?.length;
    noSelect = centreUserRows?.length;
    return {
      selected,
      noSelect,
    };
  }, [joinCheckBoxKeys, copyCheckBoxKeys, centreUserRows, centreUserRowsCopy]);

  /**
   * 搜索下拉菜单
   */
  const autoOptionRight = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        const name = item?.realName;
        if (name?.includes(rightSearchValue)) {
          const nameLength = name?.length;
          const select = name?.search(rightSearchValue);
          const searchLength = rightSearchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = rightSearchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id,
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(joinCheckBoxRows);
    return option;
  }, [joinCheckBoxRows, rightSearchValue]);
  /**
   *  点击搜索
   * @param value
   * @param option
   */
  const onAutoSelectRight = (value: string, option: any) => {
    const optionId = option?.key;
    setRightSearchValue(value);
    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };
  /**
   * 滚动定位
   * @param id
   */
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'cardRightUser');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };
  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setRightSearchValue(e.target.value);
  };
  /**
   * 判断
   */
  const rightRows = useMemo(() => {
    // let checkRows: any = modalType ? joinCheckBoxRows : copyCheckBoxRows
    let centreList: any = centreUserRows;
    let renderList: any = [];
    centreList?.forEach((item: any) => {
      if (joinCheckBoxKeys?.includes(item?.id)) {
        renderList?.push(item);
      }
    });
    return renderList;
  }, [joinCheckBoxRows, copyCheckBoxRows, centreUserRows, centreUserRowsCopy]);
  /**
   * 取消选中
   * @param delObj
   */
  const delRightTag = (delObj: any) => {
    let newCheckKeys: any = joinCheckBoxKeys?.filter((item: any) => {
      return item != delObj?.id;
    });
    let newCheckRows: any = joinCheckBoxRows?.filter((item: any) => {
      return item?.id != delObj?.id;
    });
    updateDispath({
      type: IActionEnum.CENTRE_CHECKBOX_KEYS,
      payload: newCheckKeys,
    });
    updateDispath({
      type: IActionEnum.CENTRE_CHECKBOX_ROWS,
      payload: newCheckRows,
    });
  };
  return (
    // <div style={{ padding: "8px", height: "100%", minWidth: "33%" }}>
    <Col span={6}>
      <Card
        bordered
        title={
          <>
            <Row style={{ display: 'flex', alignItems: 'center' }}>
              <Col span={10}>
                已选：{isLength?.selected}/{isLength?.noSelect}
              </Col>
              <Col span={14}>
                <AutoComplete
                  style={{ width: '100%' }}
                  options={autoOptionRight}
                  notFoundContent={
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                  onSelect={onAutoSelectRight}
                >
                  <Input
                    suffix={<SearchOutlined />}
                    onChange={onInputChange}
                    placeholder="请按名称搜索"
                    allowClear={true}
                  />
                </AutoComplete>
              </Col>
            </Row>
          </>
        }
      >
        <ScrollBarLayout
          style={{
            height: document.body.clientHeight * 0.4,
            padding: '10px 0px',
          }}
        >
          <div style={{ paddingBottom: '10px' }}>
            {rightRows && rightRows?.length > 0 ? (
              <>
                {rightRows.map((item: any, index: any) => {
                  const name = item?.realName;
                  const nameLength = name?.length;
                  const select = name?.search(rightSearchValue);
                  const searchLength = rightSearchValue?.length;
                  const afterStr = name?.slice(0, select);
                  const selectStr = rightSearchValue;
                  const beforeStr = name?.slice(
                    select + searchLength,
                    nameLength,
                  );
                  const titleTree =
                    select > -1 && selectStr ? (
                      <Tooltip title={name}>
                        <span className={pageStyles['over-flow-hidden']}>
                          {afterStr}
                          <span style={{ color: '#f50' }}>{selectStr}</span>
                          {beforeStr}
                        </span>
                      </Tooltip>
                    ) : (
                      <Tooltip title={name}>
                        <span className={pageStyles['over-flow-hidden']}>
                          {name}
                        </span>
                      </Tooltip>
                    );
                  return (
                    <div
                      style={{ paddingTop: index == 0 ? '0px' : '' }}
                      className={'rightFather'}
                      id={item?.id + 'cardRightUser'}
                      key={item?.id + 'cardRightUser'}
                    >
                      <div className={'rightChild'}>
                        <div className={'rightChildIcon'}>
                          <div style={{ margin: '0px 5px 0px 10px' }}>
                            <MyIcon type={'icon-user'} />
                          </div>
                          <div style={{ padding: '5px 0px', width: '100%' }}>
                            {titleTree ?? '--'}
                          </div>
                        </div>
                        <span
                          style={{
                            margin: '0px 10px',
                          }}
                        >
                          <span
                            style={{
                              margin: '0px 10px',
                              cursor: 'pointer',
                            }}
                            onClick={(e) => {
                              e?.stopPropagation();
                              delRightTag(item);
                            }}
                          >
                            <CloseOutlined />
                          </span>
                        </span>
                      </div>
                    </div>
                  );
                })}
              </>
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>
        </ScrollBarLayout>
      </Card>
    </Col>
    // {/* </div> */}
  );
};

export default JoinRemindPeopleRight;
